﻿using AutoUpdater.Entity;
using AutoUpdater.Util;
using RestSharp;
using System;
using System.Collections.Generic;

namespace PalletPrintProgram.Helper
{
    public class RestHttpHelper
    {
        public static TscResponse<T> PostJson<T>(string url,object data,Dictionary<string, string> headDict = null,int timeOut = 10000,bool writeLog = true)
        {
            try
            {
                var client = new RestClient(url);
                client.Timeout = 120000;

                string postDataString = "";
                if(data is string)
                {
                    postDataString = (string)data;
                }
                else
                {
                    postDataString = JsonHelper.ToJson(data);
                }

                var requestPost = new RestRequest("", RestSharp.Method.POST);

                if(headDict != null)
                {
                    foreach (var pair in headDict)
                    {
                        requestPost.AddHeader(pair.Key, pair.Value);
                    }
                }

                requestPost.AddParameter("application/json", postDataString, ParameterType.RequestBody);
                requestPost.Timeout = timeOut;

                IRestResponse responsePost = client.Execute(requestPost);

                if (responsePost.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    TscResponse<T> response = new TscResponse<T>();
                    response.code = -1;
                    response.message = responsePost.ErrorMessage + responsePost.Content + "错误";
                    return response;
                }
                else
                {
                    TscResponse<T> response = JsonHelper.ToObj<TscResponse<T>>(responsePost.Content);
                    return response;
                }
            }
            catch (Exception ex)
            {
                string Message = ex.Message;
                if (ex.InnerException != null)
                {
                    Message += ":" + ex.InnerException.Message;
                }
                TscResponse<T> response = new TscResponse<T>();
                response.code = -1;
                response.message = Message;
                return response;
            }
        }

        public static TscResponse<T> PostForm<T>(string url, Dictionary<string, string> keyValuePairs, Dictionary<string, string> webHeaderKeyValues = null, bool writeLog = true,int timeOut=10000)
        {
            try
            {
                var client = new RestClient(url);
                client.Timeout = timeOut;

                var requestPost = new RestRequest("", RestSharp.Method.POST);
                requestPost.Timeout = timeOut;

                if (webHeaderKeyValues != null)
                {
                    foreach (var pair in webHeaderKeyValues)
                    {
                        requestPost.AddHeader(pair.Key, pair.Value);
                    }
                }

                if (keyValuePairs != null)
                {
                    foreach (var pair in keyValuePairs)
                    {
                        requestPost.AddQueryParameter(pair.Key, pair.Value);
                    }
                }

                IRestResponse responsePost = client.Execute(requestPost);

                if (responsePost.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    TscResponse<T> response = new TscResponse<T>();
                    response.code = -1;
                    response.message = responsePost.ErrorMessage + responsePost.Content + "错误";
                    return response;
                }
                else
                {
                    TscResponse<T> response = JsonHelper.ToObj<TscResponse<T>>(responsePost.Content);
                    return response;
                }
            }
            catch (Exception ex)
            {
                string Message = ex.Message;
                if (ex.InnerException != null)
                {
                    Message += ":" + ex.InnerException.Message;
                }
                TscResponse<T> response = new TscResponse<T>();
                response.code = -1;
                response.message = Message;
                return response;
            }
        }

        public static byte[] DownloadFile(string url, object data, Dictionary<string, string> headDict = null, int timeOut = 100000, bool writeLog = true)
        {

            var restClient = new RestClient { BaseUrl = new Uri(url) };

            string postDataString = "";
            if (data is string)
            {
                postDataString = (string)data;
            }
            else
            {
                postDataString = JsonHelper.ToJson(data);
            }

            var requestPost = new RestRequest("", RestSharp.Method.POST);

            if (headDict != null)
            {
                foreach (var pair in headDict)
                {
                    requestPost.AddHeader(pair.Key, pair.Value);
                }
            }

            requestPost.AddParameter("application/json", postDataString, ParameterType.RequestBody);
            requestPost.Timeout = timeOut;

            byte[] byteArray = restClient.DownloadData(requestPost);
            return byteArray;
        }

        public static byte[] DownloadFile(string url, string fileId, string appId,string appkey)
        {
            if(string.IsNullOrEmpty(url) || string.IsNullOrEmpty(fileId) || string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(appkey))
            {
                return null;
            }
            // file 文件  MultipartFile 是   上传文件
            //appId   系统id String  是 系统id
            //timestamp 时间戳 String 是   当前时间对应的时间戳
            //token   令牌 String  是
            string token = Base64.EncodeBase64Str(MD5Helper.getMd5Hash(fileId+appId + appkey));
            string timestamp = GetTimeStamp();

            var restClient = new RestClient { BaseUrl = new Uri(url) };
            var request = new RestRequest(Method.POST);  

            request.AddParameter("appId", appId);
            request.AddParameter("token", token);
            request.AddParameter("timestamp", appId);
            request.AddParameter("fileId", fileId);

            byte[] byteArray = restClient.DownloadData(request);
            return byteArray;
        }


        /// <summary>  
        /// 获取当前时间戳  
        /// </summary>  
        /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.</param>  
        /// <returns></returns>  
        public static string GetTimeStamp(bool bflag = false)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string ret = string.Empty;
            if (bflag)
                ret = Convert.ToInt64(ts.TotalSeconds).ToString();
            else
                ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();

            return ret;
        }

        //public TscResponse<FileUploadSingleResult> UploadFile(string fileName, byte[] fileData, string contentType)
        //{
        //    var iface = GlobalClass.CurrentUser.SysInterfaceList.Where(p => p.InterfaceName.ToLower() == "新架构文件上传服务接口").FirstOrDefault();
        //    if (iface == null || string.IsNullOrEmpty(iface.InterfaceAddress))
        //    {
        //        return TscResponse<FileUploadSingleResult>.Fail("新架构文件上传服务接口配置缺失");
        //    }

        //    string appId = iface.interfaceAppKey;//"test";
        //    string AppKey = iface.interfaceAppSecret; //"ane";
        //    string timestamp = GlobalClass.GetTimeStamp();



        //    //file: qweqwe.png
        //    //appId:test
        //    //token:YzZmMjFjZjE2ZTA1NmM2Y2NkOWMzMGUwZGU4NzA3YWE =
        //    //Timestamp:1596093225015

        //    Dictionary<string, string> otherData = new Dictionary<string, string>();
        //    otherData.Add("appId", appId);
        //    otherData.Add("token", token);
        //    otherData.Add("timestamp", timestamp);

        //    return SendFile(iface.InterfaceAddress, otherData, fileData, fileName, contentType);
        //}

        //private TscResponse<FileUploadSingleResult> SendFile(string url, Dictionary<string, string> otherData, byte[] file1, string name, string contentType)
        //{
        //    try
        //    {
        //        if (string.IsNullOrEmpty(contentType))
        //        {
        //            contentType = "application/octet-stream";
        //        }

        //        var request = new RestRequest(Method.POST);

        //        if (otherData != null && otherData.Count > 0)
        //        {
        //            foreach (var pare in otherData)
        //            {
        //                //传递参数
        //                request.AddParameter(pare.Key, pare.Value);
        //            }
        //        }

        //        //txtPictures.Text为文件路径
        //        request.AddFile("file", file1, name, contentType);
        //        //calling server with restClient
        //        var restClient = new RestClient { BaseUrl = new Uri(url) };
        //        //restClient.Timeout = 200;
        //        var response = restClient.Execute(request);
        //        if (response.StatusCode == HttpStatusCode.OK)
        //        {
        //            try
        //            {
        //                //返回的路径和文件名集合，格式为["路径","文件名"]
        //                string strResult = response.Content;
        //                var result = JSONHelper.JsonStringToObject<TscResponse<FileUploadSingleResult>>(strResult);
        //                LogNet.LogHelper.PrintLog(LogNet.Loggerlevel.Debug, "FileUploadUtil", "SendFile", LogNet.LoggerMark.Business, " 文件名" + name + " 返回" + strResult);

        //                if (result.data != null && !string.IsNullOrEmpty(result.data.name))
        //                {
        //                    result.data.name = Uri.UnescapeDataString(result.data.name);
        //                }

        //                return result;
        //            }
        //            catch (Exception ex)
        //            {
        //                LogNet.LogHelper.PrintLog(LogNet.Loggerlevel.ERROR, "FileUploadUtil", "SendFile", LogNet.LoggerMark.Business, ex.ToString());
        //                return TscResponse<FileUploadSingleResult>.Fail(ex.Message);
        //            }
        //        }
        //        return TscResponse<FileUploadSingleResult>.Fail(response.StatusCode.ToString());
        //    }
        //    catch (Exception ex)
        //    {
        //        LogNet.LogHelper.PrintLog(LogNet.Loggerlevel.ERROR, "FileUploadUtil", "SendFile", LogNet.LoggerMark.Business, ex.ToString());
        //        return TscResponse<FileUploadSingleResult>.Fail(ex.Message);
        //    }
        //}

    }
}
